<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>忘记密码 - 电商平台</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .forgot-container {
            background: white;
            border-radius: 10px;
            box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
            padding: 40px;
            width: 450px;
            max-width: 90vw;
        }

        .forgot-header {
            text-align: center;
            margin-bottom: 30px;
        }

        .forgot-header h1 {
            color: #333;
            font-size: 24px;
            margin-bottom: 10px;
        }

        .forgot-header p {
            color: #666;
            font-size: 14px;
        }

        .tab-container {
            display: flex;
            margin-bottom: 30px;
            border-bottom: 1px solid #eee;
        }

        .tab {
            flex: 1;
            padding: 12px;
            text-align: center;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s;
            font-size: 14px;
            color: #666;
        }

        .tab.active {
            color: #667eea;
            border-bottom-color: #667eea;
        }

        .tab-content {
            display: none;
        }

        .tab-content.active {
            display: block;
        }

        .form-group {
            margin-bottom: 20px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            color: #333;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 14px;
            transition: border-color 0.3s;
        }

        .form-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1);
        }

        .code-group {
            display: flex;
            gap: 10px;
        }

        .code-group input {
            flex: 1;
        }

        .send-code-btn {
            padding: 12px 20px;
            background: #667eea;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-size: 14px;
            white-space: nowrap;
        }

        .send-code-btn:disabled {
            background: #ccc;
            cursor: not-allowed;
        }

        .reset-btn {
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 5px;
            font-size: 16px;
            font-weight: 500;
            cursor: pointer;
            transition: transform 0.2s;
        }

        .reset-btn:hover {
            transform: translateY(-2px);
        }

        .reset-btn:disabled {
            opacity: 0.6;
            cursor: not-allowed;
            transform: none;
        }

        .back-link {
            text-align: center;
            margin-top: 20px;
            font-size: 14px;
            color: #666;
        }

        .back-link a {
            color: #667eea;
            text-decoration: none;
            font-weight: 500;
        }

        .back-link a:hover {
            text-decoration: underline;
        }

        .error-message {
            color: #e74c3c;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        .success-message {
            color: #27ae60;
            font-size: 14px;
            margin-top: 5px;
            display: none;
        }

        .step-indicator {
            display: flex;
            justify-content: center;
            margin-bottom: 20px;
        }

        .step {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background: #eee;
            color: #666;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            margin: 0 10px;
        }

        .step.active {
            background: #667eea;
            color: white;
        }

        .step.completed {
            background: #27ae60;
            color: white;
        }
    </style>
</head>
<body>
<div class="forgot-container">
    <div class="forgot-header">
        <h1>找回密码</h1>
        <p>选择找回密码的方式</p>
    </div>

    <div class="tab-container">
        <div class="tab active" data-tab="question">安全问题</div>
        <div class="tab" data-tab="phone">手机验证</div>
        <div class="tab" data-tab="email">邮箱验证</div>
    </div>

    <!-- 安全问题找回 -->
    <div class="tab-content active" id="question-content">
        <div class="step-indicator">
            <div class="step active">1</div>
            <div class="step">2</div>
            <div class="step">3</div>
        </div>

        <div id="question-step1">
            <div class="form-group">
                <label for="question-username">用户名</label>
                <input type="text" id="question-username" placeholder="请输入用户名">
                <div class="error-message" id="question-username-error"></div>
            </div>
            <button class="reset-btn" onclick="getSecurityQuestion()">下一步</button>
        </div>

        <div id="question-step2" style="display: none;">
            <div class="form-group">
                <label>安全问题</label>
                <div id="security-question" style="padding: 12px; background: #f8f9fa; border-radius: 5px; margin-bottom: 15px;"></div>
            </div>
            <div class="form-group">
                <label for="question-answer">答案</label>
                <input type="text" id="question-answer" placeholder="请输入安全问题答案">
                <div class="error-message" id="question-answer-error"></div>
            </div>
            <button class="reset-btn" onclick="verifySecurityAnswer()">下一步</button>
        </div>

        <div id="question-step3" style="display: none;">
            <div class="form-group">
                <label for="question-new-password">新密码</label>
                <input type="password" id="question-new-password" placeholder="6-12位英文和数字">
                <div class="error-message" id="question-new-password-error"></div>
            </div>
            <div class="form-group">
                <label for="question-confirm-password">确认密码</label>
                <input type="password" id="question-confirm-password" placeholder="请再次输入新密码">
                <div class="error-message" id="question-confirm-password-error"></div>
            </div>
            <button class="reset-btn" onclick="resetPasswordByQuestion()">重置密码</button>
        </div>
    </div>

    <!-- 手机验证找回 -->
    <div class="tab-content" id="phone-content">
        <div class="step-indicator">
            <div class="step active">1</div>
            <div class="step">2</div>
            <div class="step">3</div>
        </div>

        <div id="phone-step1">
            <div class="form-group">
                <label for="phone-number">手机号</label>
                <input type="tel" id="phone-number" placeholder="请输入手机号">
                <div class="error-message" id="phone-number-error"></div>
            </div>
            <button class="reset-btn" onclick="sendPhoneCode()">发送验证码</button>
        </div>

        <div id="phone-step2" style="display: none;">
            <div class="form-group">
                <label for="phone-code">验证码</label>
                <div class="code-group">
                    <input type="text" id="phone-code" placeholder="请输入验证码">
                    <button class="send-code-btn" id="phone-resend-btn" onclick="sendPhoneCode()">重新发送</button>
                </div>
                <div class="error-message" id="phone-code-error"></div>
            </div>
            <button class="reset-btn" onclick="verifyPhoneCode()">下一步</button>
        </div>

        <div id="phone-step3" style="display: none;">
            <div class="form-group">
                <label for="phone-new-password">新密码</label>
                <input type="password" id="phone-new-password" placeholder="6-12位英文和数字">
                <div class="error-message" id="phone-new-password-error"></div>
            </div>
            <div class="form-group">
                <label for="phone-confirm-password">确认密码</label>
                <input type="password" id="phone-confirm-password" placeholder="请再次输入新密码">
                <div class="error-message" id="phone-confirm-password-error"></div>
            </div>
            <button class="reset-btn" onclick="resetPasswordByPhone()">重置密码</button>
        </div>
    </div>

    <!-- 邮箱验证找回 -->
    <div class="tab-content" id="email-content">
        <div class="step-indicator">
            <div class="step active">1</div>
            <div class="step">2</div>
            <div class="step">3</div>
        </div>

        <div id="email-step1">
            <div class="form-group">
                <label for="email-address">邮箱地址</label>
                <input type="email" id="email-address" placeholder="请输入邮箱地址">
                <div class="error-message" id="email-address-error"></div>
            </div>
            <button class="reset-btn" onclick="sendEmailCode()">发送验证码</button>
        </div>

        <div id="email-step2" style="display: none;">
            <div class="form-group">
                <label for="email-code">验证码</label>
                <div class="code-group">
                    <input type="text" id="email-code" placeholder="请输入验证码">
                    <button class="send-code-btn" id="email-resend-btn" onclick="sendEmailCode()">重新发送</button>
                </div>
                <div class="error-message" id="email-code-error"></div>
            </div>
            <button class="reset-btn" onclick="verifyEmailCode()">下一步</button>
        </div>

        <div id="email-step3" style="display: none;">
            <div class="form-group">
                <label for="email-new-password">新密码</label>
                <input type="password" id="email-new-password" placeholder="6-12位英文和数字">
                <div class="error-message" id="email-new-password-error"></div>
            </div>
            <div class="form-group">
                <label for="email-confirm-password">确认密码</label>
                <input type="password" id="email-confirm-password" placeholder="请再次输入新密码">
                <div class="error-message" id="email-confirm-password-error"></div>
            </div>
            <button class="reset-btn" onclick="resetPasswordByEmail()">重置密码</button>
        </div>
    </div>

    <div class="error-message" id="general-error"></div>
    <div class="success-message" id="general-success"></div>

    <div class="back-link">
        <a href="login.html">返回登录</a>
    </div>
</div>

<script>
    let currentTab = 'question';
    let currentStep = 1;
    let countdown = 0;
    let countdownTimer;

    // 标签切换
    document.querySelectorAll('.tab').forEach(tab => {
        tab.addEventListener('click', function() {
            const tabName = this.getAttribute('data-tab');
            switchTab(tabName);
        });
    });

    function switchTab(tabName) {
        // 更新标签状态
        document.querySelectorAll('.tab').forEach(tab => {
            tab.classList.remove('active');
        });
        document.querySelector(`[data-tab="${tabName}"]`).classList.add('active');

        // 更新内容
        document.querySelectorAll('.tab-content').forEach(content => {
            content.classList.remove('active');
        });
        document.getElementById(`${tabName}-content`).classList.add('active');

        currentTab = tabName;
        currentStep = 1;
        resetSteps();
        clearMessages();
    }

    function resetSteps() {
        // 重置所有步骤显示
        document.querySelectorAll('[id$="-step1"], [id$="-step2"], [id$="-step3"]').forEach(el => {
            el.style.display = 'none';
        });

        // 显示第一步
        document.querySelectorAll('[id$="-step1"]').forEach(el => {
            if (el.closest('.tab-content.active')) {
                el.style.display = 'block';
            }
        });

        // 重置步骤指示器
        document.querySelectorAll('.step').forEach((step, index) => {
            step.classList.remove('active', 'completed');
            if (index === 0) step.classList.add('active');
        });
    }

    function updateSteps(step) {
        currentStep = step;

        // 隐藏所有步骤
        document.querySelectorAll('[id$="-step1"], [id$="-step2"], [id$="-step3"]').forEach(el => {
            el.style.display = 'none';
        });

        // 显示当前步骤
        document.querySelector(`#${currentTab}-step${step}`).style.display = 'block';

        // 更新步骤指示器
        document.querySelectorAll('.step').forEach((stepEl, index) => {
            stepEl.classList.remove('active', 'completed');
            if (index < step - 1) {
                stepEl.classList.add('completed');
            } else if (index === step - 1) {
                stepEl.classList.add('active');
            }
        });
    }

    // 安全问题找回
    async function getSecurityQuestion() {
        const username = document.getElementById('question-username').value.trim();

        if (!username) {
            showError('question-username-error', '请输入用户名');
            return;
        }

        try {
            const response = await fetch(`/api/user/forgot-password/question?account=${encodeURIComponent(username)}`);
            const result = await response.json();

            if (result.code === 200) {
                document.getElementById('security-question').textContent = result.data;
                updateSteps(2);
            } else {
                showError('question-username-error', result.message);
            }
        } catch (error) {
            showError('question-username-error', '网络错误，请重试');
        }
    }

    async function verifySecurityAnswer() {
        const username = document.getElementById('question-username').value.trim();
        const answer = document.getElementById('question-answer').value.trim();

        if (!answer) {
            showError('question-answer-error', '请输入安全问题答案');
            return;
        }

        try {
            const response = await fetch('/api/user/forgot-password/verify', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    account: username,
                    asw: answer
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                updateSteps(3);
            } else {
                showError('question-answer-error', result.message);
            }
        } catch (error) {
            showError('question-answer-error', '网络错误，请重试');
        }
    }

    async function resetPasswordByQuestion() {
        const username = document.getElementById('question-username').value.trim();
        const newPassword = document.getElementById('question-new-password').value.trim();
        const confirmPassword = document.getElementById('question-confirm-password').value.trim();

        if (!validatePassword(newPassword, confirmPassword, 'question')) {
            return;
        }

        try {
            const response = await fetch('/api/user/forgot-password/reset', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    account: username,
                    newPassword: newPassword,
                    confirmPassword: confirmPassword,
                    type: 'QUESTION'
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                showSuccess('general-success', '密码重置成功！正在跳转到登录页面...');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000);
            } else {
                showError('general-error', result.message);
            }
        } catch (error) {
            showError('general-error', '网络错误，请重试');
        }
    }

    // 手机验证找回
    async function sendPhoneCode() {
        const phone = document.getElementById('phone-number').value.trim();

        if (!phone) {
            showError('phone-number-error', '请输入手机号');
            return;
        }

        if (!/^1[0-9]{10}$/.test(phone)) {
            showError('phone-number-error', '手机号格式不正确');
            return;
        }

        try {
            const response = await fetch('/api/user/forgot-password/phone-code', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    phone: phone
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                if (currentStep === 1) {
                    updateSteps(2);
                }
                startCountdown('phone-resend-btn');
                showSuccess('general-success', '验证码已发送');
            } else {
                showError('phone-number-error', result.message);
            }
        } catch (error) {
            showError('phone-number-error', '网络错误，请重试');
        }
    }

    async function verifyPhoneCode() {
        const phone = document.getElementById('phone-number').value.trim();
        const code = document.getElementById('phone-code').value.trim();

        if (!code) {
            showError('phone-code-error', '请输入验证码');
            return;
        }

        try {
            const response = await fetch('/api/user/forgot-password/verify', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    phone: phone,
                    verificationCode: code,
                    type: 'PHONE'
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                updateSteps(3);
            } else {
                showError('phone-code-error', result.message);
            }
        } catch (error) {
            showError('phone-code-error', '网络错误，请重试');
        }
    }

    async function resetPasswordByPhone() {
        const phone = document.getElementById('phone-number').value.trim();
        const code = document.getElementById('phone-code').value.trim();
        const newPassword = document.getElementById('phone-new-password').value.trim();
        const confirmPassword = document.getElementById('phone-confirm-password').value.trim();

        if (!validatePassword(newPassword, confirmPassword, 'phone')) {
            return;
        }

        try {
            const response = await fetch('/api/user/forgot-password/reset', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    phone: phone,
                    verificationCode: code,
                    newPassword: newPassword,
                    confirmPassword: confirmPassword,
                    type: 'PHONE'
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                showSuccess('general-success', '密码重置成功！正在跳转到登录页面...');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000);
            } else {
                showError('general-error', result.message);
            }
        } catch (error) {
            showError('general-error', '网络错误，请重试');
        }
    }

    // 邮箱验证找回
    async function sendEmailCode() {
        const email = document.getElementById('email-address').value.trim();

        if (!email) {
            showError('email-address-error', '请输入邮箱地址');
            return;
        }

        if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
            showError('email-address-error', '邮箱格式不正确');
            return;
        }

        try {
            const response = await fetch('/api/user/forgot-password/email-code', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    email: email
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                if (currentStep === 1) {
                    updateSteps(2);
                }
                startCountdown('email-resend-btn');
                showSuccess('general-success', '验证码已发送到邮箱');
            } else {
                showError('email-address-error', result.message);
            }
        } catch (error) {
            showError('email-address-error', '网络错误，请重试');
        }
    }

    async function verifyEmailCode() {
        const email = document.getElementById('email-address').value.trim();
        const code = document.getElementById('email-code').value.trim();

        if (!code) {
            showError('email-code-error', '请输入验证码');
            return;
        }

        try {
            const response = await fetch('/api/user/forgot-password/verify', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    email: email,
                    verificationCode: code,
                    type: 'EMAIL'
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                updateSteps(3);
            } else {
                showError('email-code-error', result.message);
            }
        } catch (error) {
            showError('email-code-error', '网络错误，请重试');
        }
    }

    async function resetPasswordByEmail() {
        const email = document.getElementById('email-address').value.trim();
        const code = document.getElementById('email-code').value.trim();
        const newPassword = document.getElementById('email-new-password').value.trim();
        const confirmPassword = document.getElementById('email-confirm-password').value.trim();

        if (!validatePassword(newPassword, confirmPassword, 'email')) {
            return;
        }

        try {
            const response = await fetch('/api/user/forgot-password/reset', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    email: email,
                    verificationCode: code,
                    newPassword: newPassword,
                    confirmPassword: confirmPassword,
                    type: 'EMAIL'
                })
            });

            const result = await response.json();

            if (result.code === 200) {
                showSuccess('general-success', '密码重置成功！正在跳转到登录页面...');
                setTimeout(() => {
                    window.location.href = 'login.html';
                }, 2000);
            } else {
                showError('general-error', result.message);
            }
        } catch (error) {
            showError('general-error', '网络错误，请重试');
        }
    }

    function validatePassword(password, confirmPassword, prefix) {
        if (!password) {
            showError(`${prefix}-new-password-error`, '请输入新密码');
            return false;
        }

        if (!/^[a-zA-Z0-9]{6,12}$/.test(password)) {
            showError(`${prefix}-new-password-error`, '密码必须是6-12位英文和数字');
            return false;
        }

        if (!confirmPassword) {
            showError(`${prefix}-confirm-password-error`, '请确认密码');
            return false;
        }

        if (password !== confirmPassword) {
            showError(`${prefix}-confirm-password-error`, '两次输入的密码不一致');
            return false;
        }

        return true;
    }

    function startCountdown(buttonId) {
        const button = document.getElementById(buttonId);
        countdown = 60;
        button.disabled = true;

        countdownTimer = setInterval(() => {
            countdown--;
            button.textContent = `${countdown}秒后重发`;

            if (countdown <= 0) {
                clearInterval(countdownTimer);
                button.disabled = false;
                button.textContent = '重新发送';
            }
        }, 1000);
    }

    function clearMessages() {
        document.querySelectorAll('.error-message, .success-message').forEach(el => {
            el.style.display = 'none';
            el.textContent = '';
        });
    }

    function showError(elementId, message) {
        const element = document.getElementById(elementId);
        element.textContent = message;
        element.style.display = 'block';
    }

    function showSuccess(elementId, message) {
        const element = document.getElementById(elementId);
        element.textContent = message;
        element.style.display = 'block';
    }
</script>
</body>
</html>